/**
 * 表单设计 列表页
 *
 * 作者 fenghaijun
 * 日期 2024-08-28 10:54:00
 */
layui.use(['jquery', 'laydate', 'febs', 'form', 'table', 'commonJS', 'validate'], function () {
    var $ = layui.jquery,
        laydate = layui.laydate,
        febs = layui.febs,
        form = layui.form,
        table = layui.table,
        commonJS = layui.commonJS,
        validate = layui.validate,
        $view = $('#febs-formDesign'),
        $query = $view.find('#query'),
        $searchForm = $view.find('#formDesign-table-form'),
        tableIns;

    form.verify(validate);
    form.render();
    initTable();
    initDate()
    function initDate() {
        //初始化日期控件
        laydate.render({
            elem: '#laydate-range',
            range: ['#startDate', '#endDate'],
            format: 'yyyy-MM-dd',
            btns: ['now', 'confirm']
        })
        // $('#endDate').val(commonJS.getCurrentDateStr(new Date()));
        // $('#startDate').val(commonJS.getPastDateStr(new Date(), 7));
        form.render();

    }

    function initTable() {
        tableIns = febs.table.init({
            elem: $view.find('table'),
            id: 'formDesignTable',
            url: ctx + 'formDesign/list',
            where: getQueryParams(),
            height: getTableHeight(),
            skin: '',
            cols: [[
                {type: 'numbers', title: '序号'},
                {field: 'tenantName', title: '公司名称', minWidth: 260,hide:!hasHeadCompanyRole},
                {field: 'formName', title: '表单名称', minWidth: 120},
                {field: 'version', title: '适用范围', minWidth: 200,
                    templet:function (d){
                        let html=''
                        if(d.publishObject == '2'){
                            d.deptList.forEach(item =>{
                                html+=`<span class="tag" style="border-radius: 4px;padding: 5px;height: 30px;margin-bottom: 10px;background-color: #ECF5FF;box-sizing: border-box;color: #409EFF;margin-right: 12px;">${ item.deptName }</span>`
                            })
                        }else if(d.publishObject == '3'){
                            d.userList.forEach(item =>{
                                html+=`<span class="tag" style="border-radius: 4px;padding: 5px;height: 30px;margin-bottom: 10px;background-color: #ECF5FF;box-sizing: border-box;color: #409EFF;margin-right: 12px;">${ item.uname }</span>`
                            })
                        }
                        return html;
                    }},
                {field: 'startDate', title: '开始时间', width: 120},
                {field: 'endDate', title: '结束时间', width: 120},
                {field: 'status', title: '表单状态', width: 100,toolbar: '#statusOption',align: 'center'
                },
                {field: 'status', title: '设为模板', width: 100,align: 'center',toolbar: '#templateFlgOption'},
                {title: '操作', toolbar: '#formDesign-tool', align: 'center', width: 150}
            ]],
            toolbar: '#formDesign-toolbar',
            defaultToolbar: []
        });
    }

    table.on('sort(formDesignTable)', function (obj) {
        tableIns.reload({
            initSort: obj,
            where: $.extend(getQueryParams(), {
                field: obj.field,
                order: obj.type
            }),
            autoSort: true
        });
    });
    // 是否设为模板
    form.on('switch(templateFlgOption)', function (obj) {
        var checked = obj.elem.checked;
        var templateFlg;
        if (checked) {
            templateFlg = "1";
        } else {
            templateFlg = "0";
        }
        //获取该控件所在行
        var index = obj.othis.parents('tr').eq(0).data('index');
        //获取表中所有数据 按行取数据及其id
        var id = table.cache['formDesignTable'][index].designId;
        let tips = checked ? '确定设为模板' :'确定取消设置模板'
        febs.modal.confirm('提示', tips, function () {
            updateTemplateFlg(id, templateFlg);
        }, function () {
            obj.elem.checked = !checked;
            layer.closeAll();
            form.render('checkbox');
        });

    });
    function updateTemplateFlg(id,templateFlg) {
        //更新岗位状态
        let model={
            designId : id,
            templateFlg : templateFlg
        }
        febs.post(ctx + 'formDesign/updateTemplateFlg', model, function () {
            febs.alert.success('修改成功');
            $query.trigger('click');
        })
    }
    // 是否发布
    form.on('switch(statusOption)', function (obj) {
        var checked = obj.elem.checked;
        var status;
        if (checked) {
            status = "2";
        } else {
            status = "1";
        }
        //获取该控件所在行
        var index = obj.othis.parents('tr').eq(0).data('index');
        //获取表中所有数据 按行取数据及其id
        var id = table.cache['formDesignTable'][index].designId;
        let tips = checked ? '确定发布' :'确定取消发布'
        febs.modal.confirm('提示', tips, function () {
            updateStatus(id, status);
        }, function () {
            obj.elem.checked = !checked;
            layer.closeAll();
            form.render('checkbox');
        });

    });

    function updateStatus(id,status) {
        //更新岗位状态
        let model={
            designId : id,
            status : status
        }
        febs.post(ctx + 'formDesign/updateStatus', model, function () {
            febs.alert.success('修改状态成功');
            $query.trigger('click');
        })
    }
    function reloadPage(curr) {
        var _curr = $view.find(".layui-laypage-em").next().html();
        if (!!curr) {
            _curr = curr;
        }
        tableIns.reload({where: getQueryParams(), page: {curr: _curr}});
    }

    $query.on('click', function () {
        reloadPage(1);
    });

    table.on('toolbar(formDesignTable)', function (obj) {
        if (obj.event === 'add') {
            febs.modal.open('新增', 'formDesign/add', {
                btn: ['预览','保存', '取消'],
                area: ['95%','95%'],
                yes:function (index,layero){
                    $('#formDesign-edit').find('#submit').trigger('click');
                },
                btn2: function (index, layero) {
                    $('#formDesign-edit').find('#save').trigger('click');
                    return false
                },
                btn3: function () {
                    layer.closeAll();
                },
                data:{
                    tenantId: $searchForm.find('select[name="tenantId"]').val()
                }
            });
        }
    });

    table.on('tool(formDesignTable)', function (obj) {
        var data = obj.data,
        layEvent = obj.event;
        if (layEvent === 'del') {
            febs.modal.confirm('删除数据', '确定删除所选数据？', function () {
                deleteIds(data.designId);
            });
        }
        if (layEvent === 'edit') {
            febs.modal.open('修改', 'formDesign/update/' + data.designId, {
                area: ['95%','95%'],
                btn: ['预览','保存', '取消'],
                yes: function (index, layero) {
                    $('#formDesign-edit').find('#submit').trigger('click');
                },
                btn2: function (index, layero) {
                    $('#formDesign-edit').find('#save').trigger('click');
                    return false
                },
                btn3: function () {
                    layer.closeAll();
                },
                data:{
                    tenantId: $searchForm.find('select[name="tenantId"]').val()
                }
            });
        }
    });

    // $delete.on('click', function () {
    //     var checkStatus = table.checkStatus('formDesignTable');
    //     if (!checkStatus.data.length) {
    //         febs.alert.warn('没有选择要删除的数据！');
    //     } else {
    //         febs.modal.confirm('删除数据', '确定删除所选数据？', function () {
    //             var ids = [];
    //             layui.each(checkStatus.data, function (key, item) {
    //                 ids.push(item.designId);
    //             });
    //             deleteIds(ids.join(','));
    //         });
    //     }
    // });

    function getQueryParams() {
        return {
            formName: $searchForm.find('input[name="formName"]').val()?.trim(),
            tenantId: $searchForm.find("select[name='tenantId']").find("option:selected").val(),
            startDate: $searchForm.find('input[name="startDate"]').val(),
            endDate: $searchForm.find('input[name="endDate"]').val(),
            status: $searchForm.find("select[name='status']").find("option:selected").val(),
            invalidate_ie_cache: new Date()
        };
    }

    function deleteIds(ids) {
        febs.get(ctx + 'formDesign/delete/' + ids, null, function () {
            febs.alert.success('删除数据成功');
            $query.trigger('click');
        })
    }

    function getTableHeight() {
        return commonJS.calcTableHeight();
    }

    $(window).resize(function () {
        tableIns.reload({height: getTableHeight()});
    });
});